package com.me.customerdemo.interceptor;


import com.me.customerdemo.pojo.User;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 登录拦截器
 * 拦截每一个请求，如时该请求对应的会话对象中没有user属性，则发出该请求
 */
public class LoginInterceptor implements HandlerInterceptor {

    // preHandler方法时在请求到达控制器之前，被框架调用，用于处理请求
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        if (user != null) {
            return true;
        }

        // 如果返回false，就表明不在继续转发请求
        response.sendRedirect("/login");
        return false;
    }
}
